import os
import sys
import threading

import requests as req
from fontTools.ttLib import TTFont


def save_dynamic_woff(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
    }
    resp = req.get(url=url, headers=headers)
    file_name = threading.currentThread().name + '_' + url.split('/')[-1]
    with open(file_name, mode='wb') as ff:
        ff.write(resp.content)
    return file_name


def get_nums_dict(file_name):
    font = TTFont(file_name)
    cmap = font.getBestCmap()
    font.close()
    os.remove(file_name)
    if len(cmap) == 72:
        key_list = []
        index_count = 0
        for k, v in cmap.items():
            key_list.append(str(chr(k)) if index_count < 36 else str(hex(k)))
            index_count += 1
        return dict(zip(key_list[36:], key_list[0:36]))
    raise ValueError('解析的字体文件有问题，请排查！')


def get_dynamic_num_dict(url):
    return get_nums_dict(save_dynamic_woff(url))


if __name__ == '__main__':
    aa = []
    for i in range(1, len(sys.argv)):
        aa.append(str(sys.argv[i]))
    print(get_dynamic_num_dict(aa[0]))
